package com.phone580.app;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

import com.phone580.app.dao.DownloadInfoDao;
import com.phone580.app.entity.DownloadInfoEntity;
import com.phone580.app.hotapp.HotAppDetailActivity;
import com.phone580.app.model.DownloadManagerModel;
import com.phone580.app.untilty.ImageCache;

public class JavascriptProxy {
	
	public Context context;
	private String notice = "该应用正在下载";
	
	public void setNotice(String notice) {
		this.notice = notice;
	}

	public JavascriptProxy (Context context) {
		this.context = context;
	}
	
	public void toDetail(String url) {
		Intent intent = new Intent(context, HotAppDetailActivity.class); 
		intent.putExtra("url", url);
		context.startActivity(intent);
	}
	
	public void cancel() {
		((Activity)context).finish();
	}
	
	public void download (String name, String icon, String url) {
		String baseURL = "http://221.179.6.75:8082/xfolder";
		ImageCache.saveImage(icon, context);
		if (!url.startsWith("http://")) {
			url = baseURL +url;
		}
		MainApplication app = (MainApplication)context.getApplicationContext();
		DownloadManagerModel model = new DownloadManagerModel(context);
		if (model.isDownloading(url)) {
			Toast.makeText(context, notice, Toast.LENGTH_SHORT).show();
			return;
		}
		String fileName = name.contains(".apk") ? name : name + ".apk";
		int count = model.checkIsExist(url);
		if (count > 0) {
			fileName = model.createNewFileName(fileName, count);
		}
		Toast.makeText(context, "下载  " + fileName, Toast.LENGTH_SHORT).show();
		DownloadInfoEntity entity = new DownloadInfoEntity();
		entity.setStatus(Constant.DOWNLOAD_STANDBY);
		entity.setUrl(url);
		entity.setFileName(fileName);
		entity.setFilePath(CommonData.APP_PATH + fileName);
		entity.setIcon(icon);
		entity.setCompleteSize(0);
		long id = model.addDownload(entity);
		entity.setId(id);
//		app.callback.startDownload(entity);
//		FutureTask<Object> future = new FutureTask<Object>(new Worker(entity), null);
//		app.getThreadPool().execute(future);
//		Downloader.start(context, entity);
		app.startDownload(entity);
	}
}
